#nullable enable

using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components;
using Application.Service.Users;
using Application.Service.Permissions;
using Microsoft.JSInterop;
using Application.Service.LogCache;
using Application.Web.Core.Services;
using System.Diagnostics.CodeAnalysis;

namespace Application.Web.Entry.Shared
{
    /// <summary>
    /// 
    /// </summary>
    public sealed partial class MainLayout
    {
        //是否开启多标签模式
        private bool UseTabSet { get; set; } = true;

        private string Theme { get; set; } = "";

        private bool IsOpen { get; set; }

        private bool OpenMessages { get; set; }

        //是否固定 Header 组件
        private bool IsFixedHeader { get; set; } = true;

        //是否固定多标签 Header
        private bool IsFixedTabHeader { get; set; } = true;

        //是否固定 Footer 组件
        private bool IsFixedFooter { get; set; } = true;

        //侧边栏是否占满整个左边
        private bool IsFullSide { get; set; } = true;

        //是否显示 Footer 模板
        private bool ShowFooter { get; set; } = true;

        private bool ShowTabInHeader { get; set; } = true;

        [Inject]
        [NotNull]
        private IServiceProvider? ServiceProvider { get; set; }

        private List<MenuItem>? _menus { get; set; }

        // 演示当前登录用户信息（集成认证时请替换为真实来源）
        private int CurrentUserId { get; set; } = -1;
        private string CurrentUserName { get; set; } = "Admin";

        private string CurrentUserDisplayName { get; set; } = "超级管理员";

        // 与 razor 中 @ref 对应
        private Modal? SmallModal { get; set; }

        // 修改密码模态框组件引用
        private PasswordChangeModal? PasswordChangeModalRef { get; set; }

        [Inject]
        private ILogger<MainLayout>? Logger { get; set; }

        [Inject]
        private UserService? _userService { get; set; }

        [Inject]
        private IJSRuntime? JSRuntime { get; set; }

        [Inject]
        private ToastService? ToastService { get; set; }

        /// <summary>
        /// OnInitializedAsync 方法
        /// </summary>
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
        }

        private async Task LoadMenusAsync()
        {
            // 防止菜单重复加载 - 只有当菜单完全未初始化时才加载
            _menus = await GetIconSideMenuItemsAsync();
            StateHasChanged();
        }

        /// <summary>
        /// OnAfterRenderAsync 方法 - 在组件渲染完成后执行
        /// </summary>
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            await base.OnAfterRenderAsync(firstRender);

            if (firstRender)
            {
                // 从localStorage获取当前用户ID（在客户端渲染完成后执行）
                await LoadCurrentUserInfo();
                // 确保菜单只在初始化时加载一次，防止菜单重复加载 - 只有当菜单完全未初始化时才加载
                if (_menus == null || _menus.Count == 0)
                {
                    await LoadMenusAsync();
                }
            }
        }

        private async Task LoadCurrentUserInfo()
        {
            if (JSRuntime != null)
            {
                try
                {
                    // 获取当前用户ID
                    var userIdStr = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "currentUserId");
                    if (!string.IsNullOrEmpty(userIdStr) && int.TryParse(userIdStr, out int userId) && userId > 0)
                    {
                        CurrentUserId = userId;
                    }

                    // 获取当前用户名
                    var username = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "currentUserName");
                    if (!string.IsNullOrEmpty(username))
                    {
                        CurrentUserName = username;
                    }

                    // 获取当前用户显示名
                    var displayName = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "currentDisplayName");
                    if (!string.IsNullOrEmpty(displayName))
                    {
                        CurrentUserDisplayName = displayName;
                    }

                    // 根据用户ID获取用户详细信息
                    if (_userService != null && CurrentUserId > 0 && string.IsNullOrEmpty(displayName))
                    {
                        var user = await _userService.GetAsync(CurrentUserId);
                        if (user != null)
                        {
                            CurrentUserDisplayName = user.DisplayName ?? user.UserName;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger?.LogError(ex, "加载用户信息失败");
                }
            }
        }

        private async Task<List<MenuItem>> GetIconSideMenuItemsAsync()
        {
            if (_menus != null && _menus.Count > 0)
                return _menus;
            var menus = new List<MenuItem>
            {
                new() { Text = "首页", Icon = "fa-solid fa-fw fa-home", Url = "/" , Match = NavLinkMatch.All}
            };

            // 检查用户权限并动态添加菜单项
            var checkPermission = ServiceProvider.GetRequiredService<CheckPermission>();

            // 检查用户管理权限
            if (await checkPermission.CanAccessPageAsync("user"))
            {
                menus.Add(new() { Text = "用户管理", Icon = "fa-solid fa-fw fa-users", Url = "/users" });
            }

            // 检查权限管理权限
            if (await checkPermission.CanAccessPageAsync("permission"))
            {
                menus.Add(new() { Text = "权限管理", Icon = "fa-solid fa-fw fa-user-gear", Url = "/permissions" });
            }

            // 检查日志查看权限
            if (await checkPermission.CanAccessPageAsync("log"))
            {
                menus.Add(new() { Text = "系统日志", Icon = "fa-solid fa-fw fa-database", Url="/systemlogs" });
            }

            // 添加其他固定菜单项
            menus.AddRange(new List<MenuItem>
            {
                
                new() { Text = "API接口", Icon = "fa-solid fa-fw fa-code", Url = "/swagger_api" },
                new() { Text = "日志缓存测试", Icon= "fa-solid fa-fw fa-file-lines" ,Url="/log-test"}
            });

            return menus;
        }

        private Task OnSideChanged(bool v)
        {
            IsFullSide = v;
            StateHasChanged();
            return Task.CompletedTask;
        }

        // 安全打开个人中心弹窗（避免直接在模板中引用可能的 null 引用）
        private async Task ShowPersonalCenter()
        {
            if (PasswordChangeModalRef != null)
            {
                await PasswordChangeModalRef.ShowAsync();
            }
        }

        private async Task HandlePasswordChanged()
        {
            await Task.Run(() => LogWrapper.Information("密码修改成功"));
        }

        // ErrorBoundary 的错误回调，记录日志，必要时可以弹窗或上报
        private async Task HandleError(Exception ex)
        {
            LogWrapper.Error("ErrorBoundary 发生未处理异常", ex);
            // Logger?.LogError(ex, "Unhandled exception in MainLayout");
            // 不自动 Recover，保留 ErrorContent 展示异常供调试；
            await Task.CompletedTask;
        }
    }
}
